from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from apps.config.models import Jobs_model
from django.core.cache import cache
# 页面
from apps.config.serializers import Menu_serializer


def jobs_view(request):
    menu_list = cache.get('menu_list')
    menu_obj = Menu_serializer(menu_list, many=True)
    return render(request, 'jobs/list.html', {'data': menu_obj.data})

# 查所有
def jobs_list(request):
    try:
        jobs = Jobs_model.objects.filter()
        count = Jobs_model.objects.count()
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'job全查模块出现问题，请联系管理员！'})
    list1 = []
    for i in jobs:
        dict = {}
        dict['id'] = i.id
        dict['job_code'] = i.job_code
        dict['job_name'] = i.job_name
        dict['remark_describe'] = i.remark_describe
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        list1.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})

# 添加界面
def jobs_insert_view(request):
    return render(request,'jobs/insert.html')

# 添加动作

def jobs_insert(request):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50500501' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code=request.POST.get('job_code')
    name=request.POST.get('job_name')
    try:
        job_obj=Jobs_model.objects.create(job_code=code,job_name=name)
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查岗位代码。'})
        else:
            return JsonResponse({'code': 203, 'msg': '未知错误！'})
    return JsonResponse({'code': 0, 'msg': '添加成功！'})

# 修改视图
def jobs_edit_view(request):
    return render(request,'jobs/edit.html')

# 修改动作
@transaction.atomic
def jobs_edit(request,id):
    # 判断是否有权限id
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    if '50500502' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    code = request.POST.get('job_code')
    name = request.POST.get('job_name')
    try:
        job_obj = Jobs_model.objects.get(pk=id)
        job_obj.job_code = code
        job_obj.job_name = name
        job_obj.save()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        if e.args[0] == 1062:
            return JsonResponse({'code': 202, 'msg': '唯一值出现重复！请检查岗位代码。'})
        else:
            return JsonResponse({'code': 203, 'msg': '添加失败，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '修改成功！'})

# 删除动作
@transaction.atomic
def jobs_del(request,id):
    # 先得判断是否具有添加权限（50500503）
    m_list = cache.get('menu_list')
    per_list = []
    for i in m_list:
        per_list.append(i.menu_code)
    # 判断其是否拥有权限
    if '50500503' not in per_list:
        return JsonResponse({'code': 201, 'msg': '您无此权限，请联系管理员！'})
    spoint_1 = transaction.savepoint()  # 可以设置多个保存点
    try:
        Jobs_model.objects.get(pk=id).delete()
    except Exception as e:
        transaction.savepoint_rollback(spoint_1)  # 可以回滚到指定的保存点
        return JsonResponse({'code': 202, 'msg': 'jobs删除模块出现问题，请联系管理员！'})
    return JsonResponse({'code': 0, 'msg': '删除成功！'})

# 查询
def jobs_search(request):
    name = request.GET.get('searchname')
    try:
        if len(name) == 0:
            role_list = Jobs_model.objects.filter()
        else:
            role_list = Jobs_model.objects.filter(Q(job_code__contains=name) | Q(job_name__contains=name))
        count = len(list(role_list))
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': 'jobs单查模块出现问题，请联系管理员！'})
    list1 = []
    for i in role_list:
        dict = {}
        dict['id'] = i.id
        dict['job_code'] = i.job_code
        dict['job_name'] = i.job_name
        dict['remark_describe'] = i.remark_describe
        dict['create_time'] = i.create_time.strftime("%Y-%m-%d %H:%M:%S")
        list1.append(dict)
    pageIndex = request.GET.get('page')  # pageIndex = request.POST.get('pageIndex')
    pageSize = request.GET.get('limit')  # pageSize = request.POST.get('pageSize')
    pageInator = Paginator(list1, pageSize)
    contacts = pageInator.page(pageIndex)
    res = []
    for contact in contacts:
        res.append(contact)
    return JsonResponse({'code': 0, 'msg': '成功！', 'count': count, 'data': res})

# 下拉框
def jobs_list1(request):
    try:
        jobs_list = Jobs_model.objects.filter(now_status=0)
    except Exception as e:
        return JsonResponse({'code': 201, 'msg': '下拉框查询失败，请联系管理员！'})
    list = []
    for i in jobs_list:
        # 获取当前账户的id
        dict = {}
        dict['id'] = i.id
        dict['job_code'] = i.job_code
        dict['job_name'] = i.job_name
        dict['selected'] = 'false'
        list.append(dict)
    Result = {'code': 0, 'msg': '成功！', 'data': list}
    return JsonResponse(Result)